package com.blrs.framework.web.service;

import com.blrs.common.core.domain.entity.SysDept;
import com.blrs.common.exception.ServiceException;
import com.blrs.system.domain.SysUserRole;
import com.blrs.system.mapper.SysDeptMapper;
import com.blrs.system.mapper.SysUserRoleMapper;
import com.blrs.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.blrs.common.constant.CacheConstants;
import com.blrs.common.constant.Constants;
import com.blrs.common.constant.UserConstants;
import com.blrs.common.core.domain.entity.SysUser;
import com.blrs.common.core.domain.model.RegisterBody;
import com.blrs.common.core.redis.RedisCache;
import com.blrs.common.exception.user.CaptchaException;
import com.blrs.common.exception.user.CaptchaExpireException;
import com.blrs.common.utils.MessageUtils;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.framework.manager.AsyncManager;
import com.blrs.framework.manager.factory.AsyncFactory;
import com.blrs.system.service.ISysConfigService;
import com.blrs.system.service.ISysUserService;
import java.sql.Timestamp;
import java.util.Date;

/**
 * 注册校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private RedisCache redisCache;

    /**
     * 注册 用来公共端注册用
     */
    public String register(RegisterBody registerBody)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysDept sysDept = sysDeptMapper.selectByDeptName(registerBody.getDeptName());
        if(sysDept!=null){
            throw new RuntimeException("该企业已在平台注册！");
        }else{
            SysUser sysUser = new SysUser();//用户表

       /* // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }*/

            if (StringUtils.isEmpty(username))
            {
                msg = "用户名不能为空";
            }
            else if (StringUtils.isEmpty(password))
            {
                msg = "用户密码不能为空";
            }
            else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                    || username.length() > UserConstants.USERNAME_MAX_LENGTH)
            {
                msg = "账户长度必须在2到20个字符之间";
            }
            else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
            {
                msg = "密码长度必须在5到20个字符之间";
            }
            else if (!userService.checkUserNameUnique(sysUser))
            {
                msg = "保存用户'" + username + "'失败，注册账号已存在";
            }
            else
            {
                boolean regFlag;
                SysUser u = userService.selectUserByUserName(username);
                if (StringUtils.isNull(u)){//判断是否存在这个用户
                    //新增默认机构企业
                    SysDept dept = new SysDept();
                    dept.setParentId(Long.parseLong("0"));
                    dept.setDeptName(registerBody.getDeptName());
                    dept.setCompanyType(registerBody.getCompanyType());
                    dept.setType("1");
                    dept.setIsCertified("0");//是否认证
                    //dept.setAncestors("0");
                    //dept.setAbbreviate("0");
                    dept.setDelFlag("0");
                    dept.setStatus("0");
                    dept.setCreateBy(username);
                    dept.setCreateTime(new Timestamp(new Date().getTime()));
                    SysDept deptList = deptService.selectDeptByDeptName(dept);
                    if(StringUtils.isNull(deptList)){//如果等于空
                        deptService.insertDept(dept);
                        //设置注册用户其他信息初始化
                        sysUser.setUserName(username);
                        sysUser.setNickName(registerBody.getNickName());
                        sysUser.setPassword(SecurityUtils.encryptPassword(password));
                        //默认为管理员
                        sysUser.setIsAdmin("1");
                        sysUser.setDelFlag("0");
                        sysUser.setStatus("0");
                        sysUser.setCreateBy(username);
                        sysUser.setSex("0");
                        sysUser.setCreateTime(new Timestamp(new Date().getTime()));
                        //获取新增后的默认机构id 根据机构企业名称查
                        SysDept deptNew = new SysDept();
                        deptNew.setDeptName(registerBody.getDeptName());
                        SysDept deptData = deptService.selectDeptByDeptName(deptNew);
                        sysUser.setDeptId(deptData.getDeptId());
                        sysUser.setBelongTo(deptData.getDeptId());
                        deptNew.setDeptId(deptData.getDeptId());
                        deptNew.setBelongTo(deptData.getDeptId().toString());
                        deptService.updateDept(deptNew);
                        regFlag= userService.registerUser(sysUser);
                    }else{
                        throw new ServiceException("该企业已存在，请重新输入！");
                    }
                }else{
                    throw new ServiceException("该账号已存在，请重新输入！");
                }
                if (!regFlag)
                {
                    msg = "注册失败,请联系系统管理人员";
                }
                else
                {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
                }
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }
}
